<template>
    <div class="category-management">
        <div class="header">
            <h2>商品分类管理</h2>
            <el-button type="primary" @click="handleAdd">新增分类</el-button>
        </div>

        <!-- 分类表格 -->
        <el-table
            :data="categoryList"
            style="width: 100%"
            row-key="id"
            border
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            v-loading="loading"
        >
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="categoryName" label="分类名称"></el-table-column>
            <el-table-column prop="categoryDesc" label="分类描述"></el-table-column>
            <el-table-column prop="level" label="级别" width="100">
                <template slot-scope="{row}">
                    <el-tag :type="levelTagType(row.level)">{{ levelText(row.level) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template slot-scope="{row}">
                    <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/编辑分类对话框 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogVisible"
            width="50%"
            @close="resetForm"
        >
            <el-form
                :model="form"
                :rules="rules"
                ref="formRef"
                label-width="100px"
            >
                <el-form-item label="分类名称" prop="category_name">
                    <el-input v-model="form.categoryName" placeholder="请输入分类名称"></el-input>
                </el-form-item>
                <el-form-item label="分类描述" prop="category_desc">
                    <el-input
                        v-model="form.categoryDesc"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入分类描述"
                    ></el-input>
                </el-form-item>
                <el-form-item label="分类级别" prop="level">
                    <el-select v-model="form.level" placeholder="请选择分类级别">
                        <el-option label="一级分类" :value="1"></el-option>
                        <el-option label="二级分类" :value="2"></el-option>
                        <el-option label="三级分类" :value="3"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'CategoryManagement',
    data() {
        return {
            // 表格数据
            categoryList: [],
            loading: false,

            // 对话框相关
            dialogVisible: false,
            dialogTitle: '新增分类',
            currentId: null,

            // 表单数据
            form: {
                category_name: '',
                category_desc: '',
                level: 1
            },

            // 表单验证规则
            rules: {
                // category_name: [
                //     { required: true, message: '请输入分类名称', trigger: 'blur' },
                //     { max: 30, message: '长度不超过30个字符', trigger: 'blur' }
                // ],
                category_desc: [
                    { max: 200, message: '长度不超过200个字符', trigger: 'blur' }
                ],
                level: [
                    { required: true, message: '请选择分类级别', trigger: 'change' }
                ]
            }
        }
    },
    created() {
        this.loadCategories()
    },
    methods: {
        // 加载分类数据
        async loadCategories() {
            this.loading = true
            try {
                // 这里替换为实际的API调用
                this.$axios.post('productCategory/listProductCategory').then(r =>{
                    this.categoryList = r.data
                })
            } catch (error) {
                this.$message.error('加载分类数据失败')
            } finally {
                this.loading = false
            }
        },

        // 级别标签样式
        levelTagType(level) {
            const types = ['', 'success', 'warning', 'danger']
            return types[level] || ''
        },

        // 级别文本
        levelText(level) {
            return ['', '一级', '二级', '三级'][level] || ''
        },

        // 新增分类
        handleAdd() {
            this.dialogTitle = '新增分类'
            this.currentId = null
            this.dialogVisible = true
        },

        // 编辑分类
        handleEdit(row) {
            this.dialogTitle = '编辑分类'
            this.currentId = row.id
            this.form = {...row}
            this.dialogVisible = true
        },

        // 删除分类
        handleDelete(row) {
            this.$confirm(`确定要删除分类 "${row.category_name}" 吗?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    // 这里替换为实际的API调用
                    this.$axios.delete(`productCategory/deleteProductCategory/${row.id}`).then(r =>{
                        this.loadCategories()
                        this.$message.success('删除成功')
                    })

                } catch (error) {
                    this.$message.error('删除失败')
                }
            }).catch(() => {})
        },

        // 提交表单
        async submitForm() {
            try {
                await this.$refs.formRef.validate()

                const formData = { ...this.form }

                if (this.currentId) {
                    // 编辑
                    this.$axios.post(`productCategory/updateProductCategory`, formData).then(r =>{
                        this.$message.success('更新成功')
                        this.loadCategories();
                    })

                } else {
                    // 新增
                    this.$axios.post(`productCategory/addProductCategory`,this.form).then(r =>{
                        if (r.data === 'yes'){
                            this.$message.success('添加成功')
                        }
                    })

                }

                this.dialogVisible = false
                this.loadCategories();
            } catch (error) {
                console.error('表单验证失败', error)
            }
        },

        // 重置表单
        resetForm() {
            this.$refs.formRef?.resetFields()
            this.form = {
                category_name: '',
                category_desc: '',
                level: 1
            }
        }
    }
}
</script>

<style scoped>
.category-management {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.el-table {
    margin-top: 20px;
}
</style>